import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from .models import User
class RegisterCreateSerializer(serializers.ModelSerializer):

    #用户再进行提交的时候有3个数据:校验密码,短信验证码,是否同意协议
    #所以,我们需要定义三个字段
    password2 = serializers.CharField(label='校验密码',allow_null=False,allow_blank=False,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,allow_null=False,allow_blank=False,write_only=True)
    allow = serializers.CharField(label='是否同意协议',allow_null=False,allow_blank=False,write_only=True)
    token = serializers.CharField(label='记录登录状态的token',read_only=True)

    class Meta:
        model = User
        fields = ('id','username','password','mobile','password2','sms_code','allow','token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    #重写create方法
    def create(self, validated_data):
        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        # 修改密码
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

    #进行校验
    #1.验证手机号格式是否正确
    def validate_mobile(self,value):
        if not re.match(r'1[345789]\d{9}',value):
            raise serializers.ValidationError('手机号格式错误')
        return value
    #2.验证是否同意用户使用协议
    def validate_allow(self,value):
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    #3.验证两次密码是否一致，验证短信验证码是否一致
    def validate(self, attrs):

        if attrs['password'] !=attrs['password2']:
            raise serializers.ValidationError('两次输入密码不一致')

        redis = get_redis_connection('code')
        sms_redis = redis.get('sms_%s'%attrs['mobile'])
        if sms_redis is None:
            raise serializers.ValidationError('验证码已过期')

        if sms_redis.decode() != attrs['sms_code']:
            raise  serializers.ValidationError('验证码错误')

        return attrs


class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','mobile','email','email_active']


from django.core.mail import send_mail
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from mall import settings
from .models import Address

class UserEmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['email']

        extra_kwargs = {
            'email':{
                'required':True
            }
        }

    def update(self, instance, validated_data):
        #先保存邮箱数据
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        #再发送验证信息

        # send_mail(
        # subject, 邮件主题
        # message, 邮件内容（文本）
        # from_email, 发送方地址
        # recipient_list, 接收方地址列表
        # html_message=None): 邮件内容（超文本）
        subject = '美多商城-邮箱激活'
        message = ''
        from_email = 'qi_rui_hua@163.com'
        recipient_list = [email]
        html_message = ''

        serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
        data = {
            'id':instance.id,
            'email':email
        }
        token = serializer.dumps(data)


        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token.decode()
        html_message = '<p>尊敬的用户您好！</p>\
                        <p>&nbsp;&nbsp;感谢您使用美多商城。</p>\
                        <p>您的邮箱为：%s,请在1小时内点击此链接完成邮箱验证：</p>\
                        <p><a href="%s">%s</a></p>'%(email,verify_url,verify_url)
        send_mail(subject=subject,
                  message=message,
                  from_email=from_email,
                  recipient_list=recipient_list,
                  html_message=html_message)

        return instance


######################################新增收货地址 序列化器######################################################
class UserAddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(label='省',read_only=True)
    city = serializers.StringRelatedField(label='市',read_only=True)
    district = serializers.StringRelatedField(label='县区',read_only=True)

    province_id =serializers.IntegerField(label='省ID',required=True)
    city_id =serializers.IntegerField(label='市ID',required=True)
    district_id =serializers.IntegerField(label='县区ID',required=True)
    mobile = serializers.RegexField(label='手机号',required=True,regex=r'^1[345789]\d{9}$')

    class Meta:
        model = Address
        exclude = ['user','is_deleted','update_time','create_time']

    def create(self, validated_data):
        #* self.context 二级视图 自动的添加,一级视图需要在实例序列化器时手动传入context参数。

        user = self.context['request'].user
        validated_data['user_id']=user.id

        # address = Address.objects.create(**validated_data)
        # return address

        address =  super().create(validated_data)
        return address


